/**
 * This file is part of the hyk-proxy-framework project.
 * Copyright (c) 2010 Yin QiWen <yinqiwen@gmail.com>
 *
 * Description: ConfigService.java 
 *
 * @author yinqiwen [ 2010-8-29 | 03:10:31 PM ]
 *
 */
package com.hyk.proxy.framework.config;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hyk.proxy.framework.appdata.AppData;
import com.hyk.proxy.framework.common.Constants;

/**
 *
 */
public class ConfigService
{
	protected static Logger logger = LoggerFactory.getLogger(ConfigService.class);
	private static Config frameworkCfg = null;
	private static Map<String, Object> pluginCfgs = new HashMap<String, Object>();
	
	public static Config getFrameworkConfig()
	{
		if(null == frameworkCfg)
		{
			try
			{
				JAXBContext context = JAXBContext.newInstance(Config.class);
				Unmarshaller unmarshaller = context.createUnmarshaller();
				if(AppData.getUserFrameworkConf().exists())
				{
					frameworkCfg = (Config) unmarshaller.unmarshal(AppData.getUserFrameworkConf());
				}
				else
				{
					frameworkCfg = (Config) unmarshaller.unmarshal(Config.class
					        .getResource("/" + Constants.CONF_FILE));
				}
				
				frameworkCfg.init();
			}
			catch (Exception e)
			{
				logger.error("Failed to load default config file!", e);
			}
		}
		return frameworkCfg;
	}
	
	public static void saveFrameworkConfig()
	{
		try
		{
			frameworkCfg.init();
			JAXBContext context = JAXBContext.newInstance(Config.class);
			Marshaller marshaller = context.createMarshaller();
			marshaller.setProperty("jaxb.formatted.output", Boolean.TRUE);
			File dest = null;
			if(AppData.getAppFrameworkConf().canWrite())
			{
				dest = AppData.getAppFrameworkConf();
			}
			else
			{
				dest = AppData.getUserFrameworkConf();
			}
			FileOutputStream fos = new FileOutputStream(dest);
			// fos.write("<!-- This is generated by hyk-proxy-client GUI, it's not the orignal conf file -->\r\n".getBytes());
			marshaller.marshal(frameworkCfg, fos);
			fos.close();
		}
		catch (Exception e)
		{
			logger.error("Failed to store framework config file!", e);
		}
	}
	
	public static <T> T getXmlPluginConfig(Class<T> type, String pluginName, String cfgName)
	{
		return null;
	}
	
	public static void saveXmlPluginCfg(Object cfg, String pluginName, String cfgName)
	{
		
	}
	
	public static InputStream getPluginConfigInputStream(String pluginName, String cfgName)
	{
		return null;
	}
	
	
}
